package com.example.design.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 *防止序列化/反射技术破坏
 *
 *  最优雅的方法--------饿汉方式   ------线程安全
 */
public enum SIngleTon5 {

        INSTANCE;

        SIngleTon5(){
            System.out.println("进行初始化操作。。。。。。。。。。。。");
        }
}

class  SingletonTest{
    public static void main(String[] args) {
        SIngleTon5 s1=SIngleTon5.INSTANCE;
        SIngleTon5 s2=SIngleTon5.INSTANCE;
        System.out.println(s1==s2);

        //获取class实例
        Class<?>  c1=Singleton4.class;
        Class<?>  c2=SIngleTon5.class;

        try {
            Constructor<?>  constructor=c1.getDeclaredConstructor();
//            Constructor<?>  constructor2=c2.getDeclaredConstructor();
//            constructor2.setAccessible(true);
//            SIngleTon5 s5= (SIngleTon5) constructor2.newInstance(); java.lang.NoSuchMethodException: com.example.design.singleton.SIngleTon5.<init>()

            constructor.setAccessible(true);

            Singleton4 s4= (Singleton4) constructor.newInstance();
            Singleton4 s44= (Singleton4) constructor.newInstance();

            System.out.println(s4==s44); //false  反射链表破坏单例


        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
